<?php

require_once "./class/Object.class.php";

class Game extends Object {

	public static $maxPlayers	= 10;

	public $currentPlayers	= 0;
	
	private $playersObjects	= array();

	public function __construct( $identifier = null ) {

		parent::__construct( $identifier );
	
	}
	
	public function save() {
	
		$values	= array(
					"currentPlayers"=> $this->currentPlayers,
				);
			
		return parent::save( $values );
	
	}
	
	public function getNbPlayers() {
	
		if ( count( $this->playersObjects ) > 0 ) {
			return count( $this->playersObjects );
		} else {
			$query	= "SELECT COUNT(_identifier) as nbPlayers "
					. "FROM player WHERE "
					. "`game` = " . $this->_identifier;
			if ( $this->_conn->query( $query ) ) {
				$nbPlayers	= $this->_conn->fetch();
				return $nbPlayers["nbPlayers"];
			} else {
				return 0;
			}
		}
	
	}
	
	public function getPlayers() {
	
		if ( count( $this->playersObjects ) > 0 ) {
			return $this->playersObjects;
		} else {
			$query	= "SELECT _identifier "
					. "FROM player WHERE "
					. "`game` = " . $this->_identifier;
			if ( $this->_conn->query( $query ) ) {
				while( $player = $this->_conn->fetch() ) {
					$this->playersObjects[]	= new Player( $player['_identifier'] );
				}
				return $this->playersObjects;
			} else {
				return array();
			}
		}
	
	}
	
	public function addNewPlayer() {
	
		$this->currentPlayers	+= 1;
		$this->save();
	
	}
	
	public function sendMessage( $message ) {

		foreach( $this->getPlayers() as $player ) {
			$player->sendMessage( $message );
		}
		
	}
	
	public static function sendDeadPlayerMessage( $player ) {
	
		$deadPlayer	= new Player( $player["player"] );
		$deadGame	= new Game( $player["game"] );
		
		if ( $deadPlayer->_identifier && $deadGame->_identifier ) {
			$message	= array(
							"message" => "playerleftgame",
							"params" => array(
								"id" => $deadPlayer->_identifier,
								"nickname" => $deadPlayer->pseudo,
							),
						);
			$deadGame->sendMessage( $message );
		}
	
	}

	public static function cleanUp() {
	
		$conn	= new DB();
		$query	= "UPDATE game SET game.currentplayers = ( SELECT COUNT(*) FROM player WHERE game._identifier = player.game )";
		$conn->query( $query );
		$query	= "DELETE FROM game WHERE currentplayers = 0";
		$conn->query( $query );
	
	}
	
	public static function getAvailableGame() {
	
		Player::cleanUp();
		self::cleanUp();
		
		$conn	= new DB();
		$query	= "SELECT _identifier FROM game WHERE "
				. "currentplayers > 0 AND currentplayers < " . self::$maxPlayers . " "
				. "LIMIT 1";
		$conn->query( $query );
		
		if ( $conn->count() ) {
			$gameId		= $conn->fetch();
			$theGame	= new Game( $gameId["_identifier"] );
		} else {
			$theGame	= new Game();
			$theGame->currentPlayers	= 0;
			$theGame->save();
		}
		
		return $theGame;
	
	}

}

?>